package com.person.leetcode.editor.cn;

import java.util.HashMap;

/**
 * 3.无重复字符的最长子串
 * 2022-03-31 01:23:34
 **/
public class Sequence_0003_LongestSubstringWithoutRepeatingCharacters {
    public static void main(String[] args) {
        Solution solution = new Sequence_0003_LongestSubstringWithoutRepeatingCharacters().new Solution();
        solution.lengthOfLongestSubstring("abba");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            System.out.println(s);
            //窗口开始 游标 窗口结束 最大值
            int head = 0, i, end = 0, max = 0;
            //去重
            HashMap<Character, Integer> hash = new HashMap<>();

            for (i = head; i < s.length(); i++) {
                char c = s.charAt(i);
                if (hash.containsKey(c)) {
                    //重复了
                    if (end - head + 1 > max) {
                        max = end - head + 1;
                    }
                    //上次开始边界的右边
                    if (hash.get(c)+1>head){
                        head = hash.get(c) + 1;
                    }

                    end = i;
                    hash.put(c, i);
                } else {
                    hash.put(c, i);
                    end = i;
                }
//                System.out.println(hash.toString());
//                System.out.println((end+1) + " " + (head+1));
//                System.out.println(max);
            }

            if (end - head + 1 > max) {
                max = end - head + 1;
            }
            if(s.length() == 0){
                max = 0;
            }
//            System.out.println("out:"+max);
            return max;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
